package com.jds.test.proto;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by sunyuming on 18/8/1.
 */
public class ServerHandler4V2Heart extends SimpleChannelInboundHandler<MyBaseProtoV2.BaseProto> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyBaseProtoV2.BaseProto msg) throws Exception {

        if("Heartbeat".equals(msg.getMsg())) {
            System.out.println("* SERVER receive heart and send back");
            writeAndFlush(ctx, msg);
        } else {
            System.out.println("general msg, send RESPONSE --------\n"+msg.toString());
            MyBaseProtoV2.BaseProto.Builder builder = MyBaseProtoV2.BaseProto.newBuilder();
            builder.setCode(msg.getCode() + 1);
            builder.setMsg("SERVER:" + msg.getMsg());
            writeAndFlush(ctx, builder.build());
        }
    }

    private void writeAndFlush(ChannelHandlerContext ctx, Object o) {
        ctx.writeAndFlush(o).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(!channelFuture.isSuccess()) {
                    channelFuture.cause().printStackTrace();
                    channelFuture.channel().close();
                }
            }
        });
    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }
}